//
//  NetSyncRecord.m
//  KidReading
//
//  Created by YangShuai on 16/6/20.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "NetSyncRecord.h"
#import "ConstDefine.h"

@interface FileModel : NSObject

@property (nonatomic,strong)NSData* fileData;
@property (nonatomic,strong)NSString* keyPath;
@property (nonatomic,assign)NSInteger uid;
@property (nonatomic,assign)NSInteger bookId;
@property (nonatomic,assign)NSInteger currentPage;
@property (nonatomic,assign)NSTimeInterval recordTime;
//存储
-(instancetype)initWithUid:(NSInteger)uid BookId:(NSInteger)bookId currentPage:(NSInteger)currentPage recordTime:(long long)recordTime FileData:(NSData*)fileData;
//获取
-(instancetype)initWithUid:(NSInteger)uid BookId:(NSInteger)bookId currentPage:(NSInteger)currentPage;
@end

@implementation FileModel

-(instancetype)initWithUid:(NSInteger)uid BookId:(NSInteger)bookId currentPage:(NSInteger)currentPage recordTime:(long long)recordTime FileData:(NSData*)fileData{
    self = [super init];
    if (self) {
        self.keyPath = [NSString stringWithFormat:@"/recording/%@/%@/%@/%@.mp3",@(uid),@(bookId),@(currentPage),@(recordTime)];
        self.fileData = fileData;
    }
    return self;
}

//获取
-(instancetype)initWithUid:(NSInteger)uid BookId:(NSInteger)bookId currentPage:(NSInteger)currentPage{
    self = [super init];
    if (self) {
        self.uid = uid;
        self.bookId = bookId;
        self.currentPage = currentPage;
    }
    return self;
}

-(void)setKeyPath:(NSString *)keyPath{
    _keyPath = keyPath;
    NSArray* sepArray = [keyPath componentsSeparatedByString:@"/"];
    self.uid = [sepArray[2] integerValue];
    self.bookId = [sepArray[3] integerValue];
    self.currentPage = [sepArray[4] integerValue];
    self.recordTime = [[[sepArray lastObject] substringToIndex:13] longLongValue];
}

@end

@interface NetSyncRecord()
@property(nonatomic,strong)JRAFURLSessionManager* sessionManager;
@property(nonatomic,copy)DownloadComplete_One downloadComplete_One;
@property(nonatomic,copy)DownloadComplete_All downloadComplete_All;

@property(nonatomic,assign)NSInteger currentUid;
@property(nonatomic,assign)NSInteger currentBookId;
@property(nonatomic,strong)NSMutableDictionary* bookConfigDict;
@end

@implementation NetSyncRecord{
    NSString* _recordDirectoryPath;
    NSMutableArray* _uploadTaskArray;
    NSMutableArray* _downloadTaskArray;
    dispatch_queue_t _queue;
}
static NetSyncRecord* singleNetSynRecord = nil;
+ (NetSyncRecord*)shareSingle{
    if (singleNetSynRecord == nil) {
        @synchronized (self) {
            singleNetSynRecord = [[NetSyncRecord alloc] init];
        }
    }
    return singleNetSynRecord;
}

//init 创建文件夹
-(instancetype)init{
    self = [super init];
    if (self) {
        //
        _uploadTaskArray = [NSMutableArray new];
        _downloadTaskArray = [NSMutableArray new];
        //创建record文件夹
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        _recordDirectoryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"recording"];
        _queue = dispatch_queue_create("fileController", DISPATCH_QUEUE_CONCURRENT);
        BOOL isDirectory = NO;
        BOOL isFileExists = NO;
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:_recordDirectoryPath isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            [[NSFileManager defaultManager] removeItemAtPath:_recordDirectoryPath error:nil];
        }
        if (!isDirectory || !isFileExists) {
            [[NSFileManager defaultManager] createDirectoryAtPath:_recordDirectoryPath withIntermediateDirectories:YES attributes:nil error:NULL];
        }
    }
    return self;
}

//初始化(打开)
-(void)bookOpenInitUid:(NSInteger)uid BookId:(NSInteger)bookId{
    self.currentUid = uid;
    self.currentBookId = bookId;
    self.bookConfigDict = [self getBookConfigDictWithUid:self.currentUid BookId:self.currentBookId];
}
//关闭书本
-(void)closeBook{
    self.currentUid = 0;
    self.currentBookId = 0;
    self.bookConfigDict = nil;
}

-(NSMutableDictionary *)bookConfigDict{
    if (!_bookConfigDict) {
        _bookConfigDict = [self getBookConfigDictWithUid:self.currentUid BookId:self.currentBookId];
    }
    return _bookConfigDict;
}

-(JRAFURLSessionManager *)sessionManager{
    if (_sessionManager == nil) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        _sessionManager = [[JRAFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        _sessionManager.operationQueue.maxConcurrentOperationCount = 3;
    }
    return _sessionManager;
}

//返回创建路径
-(NSString*)getRecordStorePathWithUid:(NSInteger)uid BookId:(NSInteger)bookId CurrentPage:(NSInteger)currentPage RecordTime:(long long)recordTime{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:currentPage recordTime:recordTime FileData:nil];
    return [self getRecordPathWithFileModel:fileModel];
}

//获取已经存在的文件路径
-(NSString*)getExitRecordFilePathWithUid:(NSInteger)uid BookId:(NSInteger)bookId CurrentPage:(NSInteger)currentPage{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:currentPage];
    return [self getExistRecordPathWithFileModel:fileModel];
}


//本地文件管理
//上传MP3
-(void)uploadRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId CurrentPage:(NSInteger)currentPage RecordTime:(long long)recordTime Success:(void(^)(NSURLResponse *response, id responseData))success Failure:(void (^)(NSError* error))failure{
    //获取已经存储的录音文件
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:currentPage];
    fileModel.recordTime = recordTime;
    if ([self isExistRecordWithUid:uid BookId:bookId CurrentPage:currentPage]) {
        [self deletePastRecordFileWithUid:uid BookId:bookId currentPage:currentPage];
    }
    //同步本地配置文件
    [self updateLocalConfigWithFielModel:fileModel];
    
    NSData* recordData = [self getRecordWithUid:uid BookId:bookId CurrentPage:currentPage];
    NSString* fileRelativePath = [self getExistRecordRelativePathWithFileModel:fileModel];
    fileModel.keyPath = fileRelativePath;
    fileModel.fileData = recordData;
    
    //上传
    [self uploadRecordFileWithFileModel:fileModel Success:^(NSURLResponse *response, id responseData) {
        if (success) success(response,responseData);
    } Failure:^(NSError *error) {
        if (failure) failure(error);
    } Progress:^(CGFloat percent, int64_t requestDidSendBytes) {
        
    }];
}

//删除
-(void)deleteRecordAndConfigKeyWithFileModel:(FileModel*)fileModel{
    [self deleteBookConfig_OneKeyValue:fileModel];
    [self deleteRecordWithFileModel:fileModel];
}

//书本录音配置list处理
//本地同步list
//存储书本目录下的配置文件(存接口字典)
-(void)storeBookConfigDcit:(NSDictionary*)configDict FileModel:(FileModel*)fileModel{
    NSString* recordConfigPath = [self getBookConfigListWithFileModel:fileModel];
    [self updateDictWithDcit:configDict FilePath:recordConfigPath];
}
//存储书本目录下的配置文件(按照fileModel的参数存)
-(void)updataRecordConfigWithFileModel:(FileModel*)fileModel{
    NSString* recordConfigPath = [self getBookConfigListWithFileModel:fileModel];
    NSMutableDictionary* bookDict = self.bookConfigDict;
    NSString* deleteRecordPath = bookDict[[NSString stringWithFormat:@"%@",@(fileModel.currentPage)]];
    if (deleteRecordPath) {
        NSMutableArray* deleteList = [self getDeleteRecordPathListWithFileModel:fileModel];
        [deleteList addObject:deleteRecordPath];
        [self updateDeleteRecordList:deleteList FileModel:fileModel];
    }
    [bookDict setValue:[self getRelativePathWithFileModel:fileModel] forKey:[NSString stringWithFormat:@"%@",@(fileModel.currentPage)]];
    self.bookConfigDict = bookDict;
    [self updateDictWithDcit:bookDict FilePath:recordConfigPath];
}

//获取书本目录下的配置文件
-(NSMutableDictionary*)getBookConfigDictWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    NSString* recordConfigPath = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/record_list",@(uid),@(bookId)]];
    if ([self fileTypeWithPath:recordConfigPath] == FileType_File) {
       NSDictionary* dict = [self getLcoalDictWithFilePath:recordConfigPath];
        if (dict) {
            return [NSMutableDictionary dictionaryWithDictionary:dict];
        }
        
    }else{
        [self updateDictWithDcit:@{} FilePath:recordConfigPath];
    }
    return [NSMutableDictionary dictionaryWithDictionary:@{}];
}
//删除某一个键值对
-(void)deleteBookConfig_OneKeyValue:(FileModel*)fileModel{
    //将删除的文件加到Delete列表中
    NSMutableArray* deleteList = [self getDeleteRecordPathListWithFileModel:fileModel];
    [deleteList addObject:[self getExistRecordRelativePathWithFileModel:fileModel]];
    [self updateDeleteRecordList:deleteList FileModel:fileModel];
    //
    NSMutableDictionary* bookConfigDict = self.bookConfigDict;
    [bookConfigDict removeObjectForKey:[NSString stringWithFormat:@"%@",@(fileModel.currentPage)]];
    self.bookConfigDict = bookConfigDict;
    [self storeBookConfigDcit:bookConfigDict FileModel:fileModel];
    
}

//已删除的文件List(对应一本书)
//获取删除list
-(NSMutableArray*)getDeleteRecordPathListWithFileModel:(FileModel*)fileModel{
    NSString* recordConfigPath = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/deleteRecord_list",@(fileModel.uid),@(fileModel.bookId)]];
    if ([self fileTypeWithPath:recordConfigPath] == FileType_File) {
        NSArray* deleteList = [self getLocalArrayWithFilePath:recordConfigPath];
        if (deleteList) {
            return [NSMutableArray arrayWithArray:deleteList];
        }
    }else{
        [self updateArrayWithArray:@[] FilePath:recordConfigPath];
    }
    return [NSMutableArray arrayWithArray:@[]];
}

//存储删除List
-(void)updateDeleteRecordList:(NSArray*)deleteList FileModel:(FileModel*)fileModel{
    NSString* deleteRecordListPath = [self getDeleteBookConfigListPathWithFileModel:fileModel];
    [self updateArrayWithArray:deleteList FilePath:deleteRecordListPath];
}
//获取本地已经同步的服务器recordList
-(NSArray*)getAlreadySynaNetRecordListWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    NSString* netRecordListPath = [self getNetRecordsListPathWithUid:uid BookId:bookId];
    if ([self fileTypeWithPath:netRecordListPath] == FileType_File) {
        NSArray* deleteList = [self getLocalArrayWithFilePath:netRecordListPath];
        if (deleteList) {
            return deleteList;
        }
    }else{
        [self updateArrayWithArray:@[] FilePath:netRecordListPath];
    }
    return @[];
}
//存储同步的服务器recordList
-(void)updateNetRecordListWithUid:(NSInteger)uid BookId:(NSInteger)bookId Array:(NSArray*)netRecordList{
    NSString* netRecordListPath = [self getNetRecordsListPathWithUid:uid BookId:bookId];
    [self updateArrayWithArray:netRecordList FilePath:netRecordListPath];
}


//获取上传失败的路径List
//{bookID_page:url,bookID_page:url}
-(NSMutableDictionary*)getUploadFailedDictWithUid:(NSInteger)uid{
    NSString* uploadFailedPath = [self getOneUserUploadFailedPathWithUid:uid];
    if ([self fileTypeWithPath:uploadFailedPath] == FileType_File) {
        NSDictionary* uploadFailedDict = [self getLcoalDictWithFilePath:uploadFailedPath];
        
        if (uploadFailedDict) {
            return [NSMutableDictionary dictionaryWithDictionary:uploadFailedDict];
        }
    }else{
        [self updateDictWithDcit:@{} FilePath:uploadFailedPath];
    }
    return [NSMutableDictionary dictionaryWithDictionary:@{}];
}
//更新上传失败的路径List
-(void)updateUploadFailedRecordDict:(NSDictionary*)failedDict FileModel:(FileModel*)fileModel{
    NSString* uploadFailedPath = [self getOneUserUploadFailedPathWithUid:fileModel.uid];
    [self updateDictWithDcit:failedDict FilePath:uploadFailedPath];
}

//删除文件与服务器同步失败List
//{bookID:[url,url],bookID:[url,url]}
-(NSMutableDictionary*)getOffLineDeleteDictWithUid:(NSInteger)uid{
    NSString* deleteFailedPath = [self getOneUserOffLineDeletePathsWithUid:uid];
    if ([self fileTypeWithPath:deleteFailedPath] == FileType_File) {
        NSDictionary* deleteFailedDict = [self getLcoalDictWithFilePath:deleteFailedPath];
        
        if (deleteFailedDict) {
            return [NSMutableDictionary dictionaryWithDictionary:deleteFailedDict];
        }
    }else{
        [self updateDictWithDcit:@{} FilePath:deleteFailedPath];
    }
    return [NSMutableDictionary dictionaryWithDictionary:@{}];
}
//更新上传失败的路径List
-(void)updateOffLineDeleteRecordDict:(NSDictionary*)failedDict Uid:(NSInteger)uid{
    NSString* offLineDeletePath = [self getOneUserOffLineDeletePathsWithUid:uid];
    [self updateDictWithDcit:failedDict FilePath:offLineDeletePath];
}

//将本地的config字典转化为数组(对应服务器格式)
-(NSArray*)changeBookRecordConfigWithDict:(NSDictionary*)configDict{
    NSArray* keyArray = [configDict allKeys];
    NSMutableArray* listArray = [NSMutableArray new];
    for (NSString* key in keyArray) {
        NSDictionary* dict = @{@"page":key,@"url":[configDict valueForKey:key]};
        [listArray addObject:dict];
    }
    return listArray;
}

//将服务器格式config数组 转化为config字典
-(NSDictionary*)changeNetConfigArrayToDictionary:(NSArray*)configArray{
    NSMutableDictionary* configDict = [NSMutableDictionary new];
    for (NSDictionary* urlDict in configArray) {
        NSString* key = urlDict[@"page"];
        NSString* url = urlDict[@"url"];
        if (url) {
            [configDict setObject:url forKey:key];
        }
    }
    return configDict;
}


//该书是否有本地录音
-(BOOL)isBookRecordExistWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    NSMutableDictionary* bookDict = self.bookConfigDict;
    if (bookDict.count > 0) {
        return YES;
    }else{
        return NO;
    }
}

//判断是否包含该页录音
-(BOOL)isExistRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId CurrentPage:(NSInteger)currentPage{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:currentPage];
    NSMutableDictionary* bookDict = self.bookConfigDict;
    if ([[bookDict allKeys] containsObject:[NSString stringWithFormat:@"%@",@(fileModel.currentPage)]] && [self getRecordWithUid:fileModel.uid BookId:fileModel.bookId CurrentPage:fileModel.currentPage]) {
        return YES;
    }else{
        return NO;
    }
}
//通过服务器的相对路径判断是否重新下载某页的录音文件
-(BOOL)needChangeLoaclRecordWithFileModel:(FileModel*)fileModel FilePath:(NSString*)relativePath{

    if (![self isExistRecordWithUid:fileModel.uid BookId:fileModel.bookId CurrentPage:fileModel.currentPage]) {
        return YES;
    }else if ([self isExistRecordWithUid:fileModel.uid BookId:fileModel.bookId CurrentPage:fileModel.currentPage]){
        //服务器文件名
        NSString* fileName = [relativePath lastPathComponent];
        fileName = [fileName substringToIndex:13];
        //本地文件名
        NSString* fileName_local = [[self getExistRecordPathWithFileModel:fileModel] lastPathComponent];
        fileName_local = [fileName_local substringToIndex:13];
        if ([fileName longLongValue] > [fileName_local longLongValue]) {
            [self deleteBookConfig_OneKeyValue:fileModel];
            [self deleteRecordWithFileModel:fileModel];
            return YES;
        }
    }
    return NO;
}


//本地文件处理方法
//同步本地皮配置文件
-(void)updateLocalConfigWithFielModel:(FileModel*)fileModel{
    //更新recordConfig
    [self updataRecordConfigWithFileModel:fileModel];
}

//获取对应page的录音
-(NSData*)getRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId CurrentPage:(NSInteger)currentPage{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:currentPage];
    NSString* filePath_record = [self getExistRecordPathWithFileModel:fileModel];
    NSData* recordData = [NSData dataWithContentsOfFile:filePath_record];
    return recordData;
}

//删除对应page的录音文件(即录音文件夹)
-(void)deleteRecordWithFileModel:(FileModel*)fileModel{
    NSString* filePath_recordDirectory = [self getBookPageRecordDirectoryPathWithFilePath:fileModel];
    if ([self recordIsExistWithFileModel:fileModel]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath_recordDirectory error:nil];
    }
}

//删除该页对应的文件(非文件夹)
-(void)deletePastRecordFileWithUid:(NSInteger)uid BookId:(NSInteger)bookId currentPage:(NSInteger)currentPage{
    NSString* filePath = [self getExitRecordFilePathWithUid:uid BookId:bookId CurrentPage:currentPage];
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

//获取各种路径的方法
//通过keyPath获取文件路径
-(NSString*)getFilePathWithKeyPath:(NSString*)keyPath{
    NSArray* sepArray = [keyPath componentsSeparatedByString:@"/"];
    NSString* uid = sepArray[2];
    NSString* bookId = sepArray[3];
    NSString* currentPage = sepArray[4];
    NSString* fileName = [sepArray lastObject];
    NSString* keyPath_local = [NSString stringWithFormat:@"%@/%@/%@/%@",uid,bookId,currentPage,fileName];
    NSString* filePath = [_recordDirectoryPath stringByAppendingPathComponent:keyPath_local];
    return filePath;
}
//获取相对路径
-(NSString*)getRelativePathWithFileModel:(FileModel*)fileModel{
    return [NSString stringWithFormat:@"/recording/%@/%@/%@/%@.mp3",@(fileModel.uid),@(fileModel.bookId),@(fileModel.currentPage),@(fileModel.recordTime)];
}
//获取单页文件夹的路径
-(NSString*)getPageDirectoryRelativePathWithFileModel:(FileModel*)fileModel{
    return [NSString stringWithFormat:@"/recording/%@/%@/%@",@(fileModel.uid),@(fileModel.bookId),@(fileModel.currentPage)];
}

//获取书本recordList地址
-(NSString*)getBookConfigListWithFileModel:(FileModel*)fileModel{
    NSString* recordConfigPath = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/record_list",@(fileModel.uid),@(fileModel.bookId)]];
    return recordConfigPath;
}
//获取存储服务器recordList的地址
-(NSString*)getNetRecordsListPathWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    NSString* netRecordDire = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",@(uid),@(bookId)]];
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:netRecordDire isDirectory:&isDirectory];
    if (!isDirectory && isFileExists) {
        [[NSFileManager defaultManager] removeItemAtPath:netRecordDire error:nil];
    }
    if (!isDirectory || !isFileExists) {
        [[NSFileManager defaultManager] createDirectoryAtPath:netRecordDire withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    return [netRecordDire stringByAppendingPathComponent:@"record_list_net"];
}

//获取书本文件夹的地址
-(NSString*)getBookRecordsPathWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    return [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",@(uid),@(bookId)]];
}

//获取录音对应文件夹的地址
-(NSString*)getBookPageRecordDirectoryPathWithFilePath:(FileModel*)fileModel{
    NSString* recordPath_page = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/%@",@(fileModel.uid),@(fileModel.bookId),@(fileModel.currentPage)]];
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:recordPath_page isDirectory:&isDirectory];
    if (!isDirectory && isFileExists) {
        [[NSFileManager defaultManager] removeItemAtPath:recordPath_page error:nil];
    }
    if (!isDirectory || !isFileExists) {
        [[NSFileManager defaultManager] createDirectoryAtPath:recordPath_page withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    return recordPath_page;
}
//获取录音文件的地址(存储地址)
-(NSString*)getRecordPathWithFileModel:(FileModel*)fileModel{
    NSString* filePath_record = [self getBookPageRecordDirectoryPathWithFilePath:fileModel];
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath_record isDirectory:&isDirectory];
    if (!isDirectory && isFileExists) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath_record error:nil];
    }
    if (!isDirectory || !isFileExists) {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath_record withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    return [filePath_record stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",@(fileModel.recordTime)]];
}

//获取录音文件的地址(已存在文件地址)
-(NSString*)getExistRecordPathWithFileModel:(FileModel*)fileModel{
    NSString* filePath_recordDirectory = [self getBookPageRecordDirectoryPathWithFilePath:fileModel];
    NSString* fileName = [self.bookConfigDict objectForKey:[NSString stringWithFormat:@"%@",@(fileModel.currentPage)]];
    if (fileName) {
        return [filePath_recordDirectory stringByAppendingPathComponent:[fileName lastPathComponent]];
    }
    return @"";
}
//获取已存在的文件相对路径
-(NSString*)getExistRecordRelativePathWithFileModel:(FileModel*)fileModel{
    NSString* fileName = [self.bookConfigDict objectForKey:[NSString stringWithFormat:@"%@",@(fileModel.currentPage)]];
    if (fileName) {
        return fileName;
    }
    return @"";
}


//用户未上传的录音的List
-(NSString*)getOneUserUploadFailedPathWithUid:(NSInteger)uid{
    NSString* failedUploadListPath = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/recordUploadFailed_list",@(uid)]];
    return failedUploadListPath;
}

//删除后同步失败的地址List
-(NSString*)getOneUserOffLineDeletePathsWithUid:(NSInteger)uid{
    NSString* deleteFailedListPath = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/deleteFailed_list",@(uid)]];
    return deleteFailedListPath;
}

//用户本地已经删除的录音的list
-(NSString*)getDeleteBookConfigListPathWithFileModel:(FileModel*)fileModel{
    NSString* deleteRecordConfigPath = [_recordDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/deleteRecord_list",@(fileModel.uid),@(fileModel.bookId)]];
    return deleteRecordConfigPath;
}




//判断当前的文件夹page的文件夹是否存在
-(BOOL)recordIsExistWithFileModel:(FileModel*)fileModel{
    NSString* recordPath_page = [self getBookPageRecordDirectoryPathWithFilePath:fileModel];
    if ([self fileTypeWithPath:recordPath_page] == FileType_Directory && [self fileSizeAtPath:recordPath_page] > 0) {
        return YES;
    }
    return NO;
}

//判定当前文件路径文件类型
-(FileType)fileTypeWithPath:(NSString*)filePath{
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
    if (isDirectory && isFileExists) {
        return FileType_Directory;
    }
    if (!isDirectory && isFileExists) {
        return FileType_File;
    }
    return FileType_None;
}

//获取文件路径下的文件大小
-(long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//获取某文件夹下有多少个文件(文件名数组)

-(NSArray*)getAllFileNames:(NSString *)filePath
{
    NSArray *files = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:filePath error:nil];
    return files;
}


//上传
//单文件上传
-(void)uploadRecordFileWithFileModel:(FileModel*)fileModel Success:(void (^)(NSURLResponse *response, id responseData))success Failure:(void (^)(NSError *error))failure Progress:(void (^)(CGFloat percent, int64_t requestDidSendBytes))progress{
    UpYun *uy = [[UpYun alloc] init];
    
    uy.sessionBlocker = ^(NSURLSessionTask* task){
        [_uploadTaskArray addObject:task];
    };
    
    uy.successBlocker = ^(NSURLResponse *response, id responseData)
    {
//        for (NSURLSessionTask* task in _uploadTaskArray) {
//            if ([fileModel.keyPath isEqualToString:objc_getAssociatedObject(task, "keyPath")]) {
//                [_uploadTaskArray removeObject:task];
//            }
//        }
        NSMutableDictionary* uploadFailedList = [self getUploadFailedDictWithUid:fileModel.uid];
        NSString* keyStr = [NSString stringWithFormat:@"%@_%@",@(fileModel.bookId),@(fileModel.currentPage)];
        [uploadFailedList removeObjectForKey:keyStr];
        [self updateUploadFailedRecordDict:uploadFailedList FileModel:fileModel];
        
        //上传成功后与服务器通信
        NSMutableDictionary* dict = self.bookConfigDict;
        NSArray* saveArray = [self changeBookRecordConfigWithDict:dict];
        NSMutableArray* deleteArray = [self getDeleteRecordPathListWithFileModel:fileModel];
        [[NetGetPostsWithCache shareInstance] operateRecordWithBookId:fileModel.bookId SaveList:saveArray DeleteList:deleteArray Success:^(NSDictionary *retDict) {
            [self updateNetRecordListWithUid:fileModel.uid BookId:fileModel.bookId Array:retDict[@"recordinglist"]];
            [deleteArray removeAllObjects];
            [self updateDeleteRecordList:deleteArray FileModel:fileModel];
        } failure:^(NSError *error) {
            
        }];
        if (success) success(response,responseData);
    };
    uy.failBlocker = ^(NSError *error)
    {
        if (error) {
//            for (NSURLSessionTask* task in _uploadTaskArray) {
//                if ([fileModel.keyPath isEqualToString:objc_getAssociatedObject(task, "keyPath")]) {
//                    [_uploadTaskArray removeObject:task];
//                }
//            }
            //将同步失败的录音地址存储到失败list中
            NSMutableDictionary* failedDict = [self getUploadFailedDictWithUid:fileModel.uid];
            NSString* PageKey = [NSString stringWithFormat:@"%@_%@",@(fileModel.bookId),@(fileModel.currentPage)];
            [failedDict setValue:fileModel.keyPath forKey:PageKey];
            [self updateUploadFailedRecordDict:failedDict FileModel:fileModel];
            [self getUploadFailedDictWithUid:fileModel.uid];
            
            NSArray* netArray = [self changeBookRecordConfigWithDict:[self getBookConfigDictWithUid:fileModel.uid BookId:fileModel.bookId]];
            [self updateNetRecordListWithUid:fileModel.uid BookId:fileModel.bookId Array:netArray];
            
        }
        if (failure) failure(error);
    };
    uy.progressBlocker = ^(CGFloat percent, int64_t requestDidSendBytes)
    {
        if (progress) progress(percent,requestDidSendBytes);
    };
    [uy uploadFile:fileModel.fileData saveKey:fileModel.keyPath];
}

//多文件顺序上传
-(void)uploadRecordsFileWithFileModelArray:(NSArray<FileModel*>*)fileModelArray Success:(void (^)(NSURLResponse *response, id responseData, NSString* keyPath))success Failure:(void (^)(NSError *error, NSString* keyPath))failure Progress:(void (^)(CGFloat percent, int64_t requestDidSendBytes, NSString* keyPath))progress{
    for (FileModel* fileModel in fileModelArray) {
        [self uploadRecordFileWithFileModel:fileModel Success:^(NSURLResponse *response, id responseData) {
            if (success) success(response,responseData,fileModel.keyPath);
        } Failure:^(NSError *error) {
            if (failure) failure(error,fileModel.keyPath);
        } Progress:^(CGFloat percent, int64_t requestDidSendBytes) {
            if (progress) progress(percent,requestDidSendBytes,fileModel.keyPath);
        }];
    }
}
//按keyPath取消上传任务
-(void)cancelUploadTaskWithKeyPath:(NSString*)keyPath{
    for (NSURLSessionTask* task in _uploadTaskArray) {
        if ([keyPath isEqualToString:objc_getAssociatedObject(task, "keyPath")]) {
            [task cancel];
        }
    }
}
//取消全部上传任务
-(void)cancelAllUploadTask{
    for (NSURLSessionTask* task in _uploadTaskArray) {
        [task cancel];
    }
}

//同步离线数据
-(void)synaOffLineDataWithUid:(NSInteger)uid AllComplete:(void(^)())allComplete Failure:(void(^)(NSError* error))failure{
    __block NSInteger reCount = 0;
    void (^syanAllComplete)() = ^(){
        if (reCount == 2) {
            NSMutableDictionary* uploadFailedList = [self getUploadFailedDictWithUid:uid];
            NSMutableDictionary* offLineDelDict = [self getOffLineDeleteDictWithUid:uid];
            if (uploadFailedList.count == 0 && offLineDelDict.count == 0) {
                if (allComplete) allComplete();
            }
        }
    };
    
    [self reUploadFailedRecordsWithUid:uid AllUpload:^{
        reCount++;
        syanAllComplete();
    } Failure:^(NSError *error) {
        if (failure) failure(error);
    }];
    [self reDeleteRecordsWithUid:uid AllReDelete:^{
        reCount++;
        syanAllComplete();
    } Failure:^(NSError *error) {
        if (failure) failure(error);
    }];
}


//网络重新连接,将上传失败的录音重新上传
-(void)reUploadFailedRecordsWithUid:(NSInteger)uid AllUpload:(void(^)())allUpload Failure:(void(^)(NSError* error))failure{
    NSMutableDictionary* uploadFailedList = [self getUploadFailedDictWithUid:uid];
    //{bookID_page:url,bookID_page:url}
    NSArray* allKey = [uploadFailedList allKeys];
    if (allKey.count == 0) {
        if (allUpload) allUpload();
    }
    for (NSString* key in allKey) {
        NSString* keyPath = uploadFailedList[key];
        NSString* filePath = [self getFilePathWithKeyPath:keyPath];
        NSData* recordData = [NSData dataWithContentsOfFile:filePath];
        NSArray* sepArray = [key componentsSeparatedByString:@"_"];
        NSInteger bookId = [[sepArray firstObject] integerValue];
        NSInteger pageId = [[sepArray lastObject] integerValue];
        FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:pageId recordTime:[[[keyPath lastPathComponent] substringToIndex:13] longLongValue] FileData:recordData];
        [self uploadRecordFileWithFileModel:fileModel Success:^(NSURLResponse *response, id responseData) {
            NSMutableDictionary* uploadFailedList = [self getUploadFailedDictWithUid:uid];
            if (uploadFailedList.count == 0) {
                if (allUpload) allUpload();
            }
        } Failure:^(NSError *error) {
            if (failure) failure(error);
        } Progress:nil];
    }
}

//网络连接,同步删除同步失败数据(网络失败只存地址)
-(void)reDeleteRecordsWithUid:(NSInteger)uid AllReDelete:(void(^)())allReDelete Failure:(void(^)(NSError* error))failure{
    
    NSMutableDictionary* offLineDelDict = [self getOffLineDeleteDictWithUid:uid];
    NSArray* keyArray = [offLineDelDict allKeys];
    if (keyArray.count == 0) {
        if (allReDelete) allReDelete();
    }
    for (NSString* key in keyArray) {
        NSArray* offLineUrlArray = offLineDelDict[key];
        [[NetGetPostsWithCache shareInstance] operateRecordWithBookId:[key integerValue] SaveList:@[] DeleteList:offLineUrlArray Success:^(NSDictionary *retDict) {
            [self updateNetRecordListWithUid:uid BookId:[key integerValue] Array:retDict[@"recordinglist"]];
            [offLineDelDict removeObjectForKey:key];
            [self updateOffLineDeleteRecordDict:offLineDelDict Uid:uid];
            if (offLineDelDict.count == 0) {
                if (allReDelete) allReDelete();
            }
        } failure:^(NSError *error) {
            if (failure) failure(error);
        }];
    }
}


//下载
//同步服务器录音列表
-(void)synaNetRecordsListWithUid:(NSInteger)uid BookId:(NSInteger)bookId Success:(void(^)(NSArray* listArray))success Failure:(void (^)(NSError *error))failure{
    [[NetGetPostsWithCache shareInstance] operateRecordWithBookId:bookId SaveList:@[] DeleteList:@[] Success:^(NSDictionary *retDict) {
        if (retDict) {
            NSArray* recordPathArray = retDict[@"recordinglist"];
            [self updateNetRecordListWithUid:uid BookId:bookId Array:recordPathArray];
            if (success) success(recordPathArray);
        }
    } failure:^(NSError *error) {
        if (failure) failure(error);
    }];
}

//确定服务器数据是否与本地数据一致
-(BOOL)localRecordListCompareNetRecordListIsSynaWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    NSDictionary* localRecordList = self.bookConfigDict;
    NSArray* localKeyArray = [localRecordList allKeys];
    NSArray* netRecordList = [self getAlreadySynaNetRecordListWithUid:uid BookId:bookId];
    if (localKeyArray.count != netRecordList.count) {
        return NO;
    }
    for (NSString* key in localKeyArray) {
        NSString* filePath_Key = localRecordList[key];
        for (NSDictionary* pageDict in netRecordList) {
            if ([pageDict[@"page"] integerValue] == [key integerValue] && ![pageDict[@"url"] isEqualToString:filePath_Key]) {
                return NO;
            }
        }
    }
    return YES;
}

//判断是否有未上传成功的数据
-(BOOL)isNeedSyanRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    NSMutableDictionary* uploadFailedList = [self getUploadFailedDictWithUid:uid];
    NSMutableDictionary* offLineDelDict = [self getOffLineDeleteDictWithUid:uid];
    if (uploadFailedList.count == 0 && offLineDelDict.count == 0) {
        return NO;
    }
    return YES;
}

//服务器是否含有该书录音
-(void)isRecordExistOnNetWithUid:(NSInteger)uid BookId:(NSInteger)bookId CheckComplete:(void (^)(BOOL isExist))checkComplete;{

    [[NetGetPostsWithCache shareInstance] operateRecordWithBookId:bookId SaveList:@[] DeleteList:@[] Success:^(NSDictionary *retDict) {
        if (retDict) {
            NSArray* recordPathArray = retDict[@"recordinglist"];
            [self updateNetRecordListWithUid:uid BookId:bookId Array:recordPathArray];
            if (recordPathArray.count > 0) {
                if (checkComplete) checkComplete(YES);
            }else{
                if (checkComplete) checkComplete(NO);
            }
        }
    } failure:^(NSError *error) {
        if (checkComplete) checkComplete(NO);
    }];
}

//同步书本录音(根据服务器的List)
-(void)downloadRecordsWithWithUid:(NSInteger)uid BookId:(NSInteger)bookId oneCompletionHandler:(DownloadComplete_One)completionHandler allComplete:(DownloadComplete_All)allComplete{
    self.downloadComplete_One = completionHandler;
    self.downloadComplete_All = allComplete;
    
    NSMutableArray* pageArray = [NSMutableArray new];
    NSMutableArray* downloadComArray = [NSMutableArray new];
    //判断是否全部下载完成
    void (^downloadComplete)(NSArray*) = ^(NSArray* downloadComArray){
        if (pageArray.count == downloadComArray.count) {
            if (self.downloadComplete_All) self.downloadComplete_All(downloadComArray);
        }
    };
    
    //判断list中的录音文件在本地有没有
    void (^downloadEvents) (NSArray* recordPathArray) = ^(NSArray* recordPathArray){
        for (NSDictionary* pageDict in recordPathArray) {
            NSInteger page = [pageDict[@"page"] integerValue];
            NSString* path = pageDict[@"url"];
            [pageArray addObject:@(page)];
            FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:page];
            if ([self needChangeLoaclRecordWithFileModel:fileModel FilePath:path]) {
                [self downloadRecordWithRecordPath:path FileModel:fileModel completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                    if (!error) {
                        [downloadComArray addObject:@(page)];
                    }
                    downloadComplete(downloadComArray);
                    if (self.downloadComplete_One) self.downloadComplete_One(response,filePath,page,downloadComArray,error);
                }];
            }else{
                [downloadComArray addObject:@(page)];
            }
        }
    };
    
    NSArray* netRecordArray = [self getAlreadySynaNetRecordListWithUid:uid BookId:bookId];
    if (netRecordArray) {
        NSMutableDictionary* localConfigDict = self.bookConfigDict;
        NSArray* localKeyArray = [self changeAllKeysArrayToStingArray:[localConfigDict allKeys]];
        
        NSDictionary* netConfigDcit = [self changeNetConfigArrayToDictionary:netRecordArray];
        NSArray* netAllKeys = [self changeAllKeysArrayToStingArray:[netConfigDcit allKeys]];
        for (NSString* key in localKeyArray) {
            if (![netAllKeys containsObject:key]) {
                [self deletePageRecordWithUid:uid BookId:bookId PageId:[key integerValue]];
            }
        }
        downloadEvents(netRecordArray);
    }
}

//根据页码同步书本
-(void)downloadRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId PageId:(NSInteger)pageId completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
    
    void (^downloadEvents) (NSArray* recordPathArray) = ^(NSArray* recordPathArray){
        //判断list中的录音文件在本地有没有
        for (NSDictionary* pageDict in recordPathArray) {
            NSInteger page = [pageDict[@"page"] integerValue];
            if (pageId == page) {
                NSString* path = pageDict[@"url"];
                FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:pageId];
                if ([self needChangeLoaclRecordWithFileModel:fileModel FilePath:path]) {
                    [self downloadRecordWithRecordPath:path FileModel:fileModel completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                        if (completionHandler) completionHandler(response,filePath,error);
                    }];
                }
            }
        }
    };
    
    NSArray* netRecordArray = [self getAlreadySynaNetRecordListWithUid:uid BookId:bookId];
    if (netRecordArray) {
        NSMutableDictionary* localConfigDict = self.bookConfigDict;
        NSArray* localKeyArray = [self changeAllKeysArrayToStingArray:[localConfigDict allKeys]];
        
        
        NSDictionary* netConfigDcit = [self changeNetConfigArrayToDictionary:netRecordArray];
        NSArray* netAllKeys = [self changeAllKeysArrayToStingArray:[netConfigDcit allKeys]];
        for (NSString* key in localKeyArray) {
            NSNumber* keyNumber = [NSNumber numberWithInteger:[key integerValue]];
            if (![netAllKeys containsObject:key] && [keyNumber integerValue] == pageId) {
                [self deletePageRecordWithUid:uid BookId:bookId PageId:[key integerValue]];
            }
        }
        downloadEvents(netRecordArray);
    }
}

//将字典allKeys取出的Key全部转化为String
-(NSArray*)changeAllKeysArrayToStingArray:(NSArray*)allKeysArray{
    NSMutableArray* keyStrArray = [NSMutableArray new];
    for (id key in allKeysArray) {
        NSString* keyStr = [NSString stringWithFormat:@"%@",key];
        [keyStrArray addObject:keyStr];
    }
    return keyStrArray;
}


//下载
-(void)downloadRecordWithRecordPath:(NSString*)recoredPath FileModel:(FileModel*)fileModel completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
    
    NSString* recordPath = [NSString stringWithFormat:@"%@%@",[DataProcessing shareSingle].audio_file_url, recoredPath];
    NSString* pagePath = [self getBookPageRecordDirectoryPathWithFilePath:fileModel];
    NSURLSessionDownloadTask* downloadTask = [self.sessionManager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:recordPath]] progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL* pagePathUrl = [NSURL fileURLWithPath:pagePath];
        NSURL* recordPathUrl = [pagePathUrl URLByAppendingPathComponent:[response suggestedFilename]];
        return recordPathUrl;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (response) {
            fileModel.recordTime = [[[filePath lastPathComponent] substringToIndex:13] longLongValue];
            [self updataRecordConfigWithFileModel:fileModel];
            if (completionHandler) completionHandler(response,filePath,error);
        }
    }];
    [downloadTask resume];
    [_downloadTaskArray addObject:downloadTask];
}


//取消所有下载任务
-(void)cancelAllDownloadTask{
    for (NSURLSessionDownloadTask* downloadTask in _downloadTaskArray) {
        [downloadTask cancel];
    }
}
//按照书本某页取消下载任务
-(void)cancelDownloadTaskUid:(NSInteger)uid BookId:(NSInteger)bookId CurrentPage:(NSInteger)currentPage{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:currentPage];
    for (NSURLSessionDownloadTask* task in _downloadTaskArray) {
        NSString* urlStr = [task.originalRequest.URL absoluteString];
        NSString* pageDire = [self getPageDirectoryRelativePathWithFileModel:fileModel];
        if ([urlStr rangeOfString:pageDire].location != NSNotFound) {
            [task cancel];
        }
    }
}


//删除整本书的录音
-(void)deleteBookRecordsWithUid:(NSInteger)uid BookId:(NSInteger)bookId{
    
    NSDictionary* configDict = self.bookConfigDict;
    NSArray* deleteUrlArr = [configDict allValues];
    
    NSString* bookPath = [self getBookRecordsPathWithUid:uid BookId:bookId];
    [[NSFileManager defaultManager] removeItemAtPath:bookPath error:nil];
    self.bookConfigDict = nil;
    [[NetGetPostsWithCache shareInstance] deleteBookAllPageRecordWithBookId:bookId Success:^(NSDictionary *retDict) {
        [self updateNetRecordListWithUid:uid BookId:bookId Array:retDict[@"recordinglist"]];
    } failure:^(NSError *error) {
        if (error) {
            NSMutableDictionary* offLineDelDict = [self getOffLineDeleteDictWithUid:uid];
            NSArray* keyArray = [offLineDelDict allKeys];
            if ([keyArray containsObject:[NSString stringWithFormat:@"%@",@(bookId)]]) {
                NSMutableArray* bookArray = [NSMutableArray arrayWithArray:offLineDelDict[[NSString stringWithFormat:@"%@",@(bookId)]]];
                [bookArray addObjectsFromArray:deleteUrlArr];
                [offLineDelDict setValue:bookArray forKey:[NSString stringWithFormat:@"%@",@(bookId)]];
                [self updateOffLineDeleteRecordDict:offLineDelDict Uid:uid];
            }else{
                NSArray* bookArray = deleteUrlArr;
                [offLineDelDict setValue:bookArray forKey:[NSString stringWithFormat:@"%@",@(bookId)]];
                [self updateOffLineDeleteRecordDict:offLineDelDict Uid:uid];
            }
        }
    }];
}

//删除某一页的录音
-(void)deletePageRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId PageId:(NSInteger)pageId{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:pageId];
    [self deleteRecordAndConfigKeyWithFileModel:fileModel];
    
    NSMutableDictionary* dict = self.bookConfigDict;
    NSArray* saveArray = [self changeBookRecordConfigWithDict:dict];
    NSMutableArray* deleteArray = [self getDeleteRecordPathListWithFileModel:fileModel];
    [[NetGetPostsWithCache shareInstance] operateRecordWithBookId:fileModel.bookId SaveList:saveArray DeleteList:deleteArray Success:^(NSDictionary *retDict) {
        [self updateNetRecordListWithUid:uid BookId:bookId Array:retDict[@"recordinglist"]];
        [deleteArray removeAllObjects];
        [self updateDeleteRecordList:deleteArray FileModel:fileModel];
    } failure:^(NSError *error) {
        if (error) {
            NSMutableDictionary* offLineDelDict = [self getOffLineDeleteDictWithUid:uid];
            NSArray* keyArray = [offLineDelDict allKeys];
            if ([keyArray containsObject:[NSString stringWithFormat:@"%@",@(bookId)]]) {
                NSMutableArray* bookArray = [NSMutableArray arrayWithArray:offLineDelDict[[NSString stringWithFormat:@"%@",@(bookId)]]];
                [bookArray addObjectsFromArray:deleteArray];
                [deleteArray removeAllObjects];
                [self updateDeleteRecordList:deleteArray FileModel:fileModel];
                [offLineDelDict setValue:bookArray forKey:[NSString stringWithFormat:@"%@",@(bookId)]];
                [self updateOffLineDeleteRecordDict:offLineDelDict Uid:uid];
            }else{
                NSArray* bookArray = [NSArray arrayWithArray:deleteArray];
                [deleteArray removeAllObjects];
                [self updateDeleteRecordList:deleteArray FileModel:fileModel];
                [offLineDelDict setValue:bookArray forKey:[NSString stringWithFormat:@"%@",@(bookId)]];
                [self updateOffLineDeleteRecordDict:offLineDelDict Uid:uid];
            }
        }
    }];
}

//删除本地录音
-(void)deleteLoaclRecordWithUid:(NSInteger)uid BookId:(NSInteger)bookId PageId:(NSInteger)pageId{
    FileModel* fileModel = [[FileModel alloc] initWithUid:uid BookId:bookId currentPage:pageId];
    [self deleteRecordAndConfigKeyWithFileModel:fileModel];
}

//删除废弃录音
-(void)deleteRubbishRecordWithKeyPath:(NSString*)keyPath{
    [[NSFileManager defaultManager] removeItemAtPath:keyPath error:nil];
}

//写入数组
-(void)updateArrayWithArray:(NSArray*)array FilePath:(NSString*)filePath{
    
    dispatch_sync(_queue, ^{
        @try {
#if __Debug_CloseAES == 0
            NSData* data = [NSKeyedArchiver archivedDataWithRootObject:array];
            data = [data AES256EncryptWithKey:__AESKey];//加密
            [data writeToFile:filePath atomically:YES];
#else
            [array writeToFile:filePath atomically:YES];
#endif
        } @catch (NSException *exception) {
            NSLog(@"saveNetCache Error: %@",exception);
        } @finally {
            
        }
    });
}

//写入字典
-(void)updateDictWithDcit:(NSDictionary*)dict FilePath:(NSString*)filePath{
    
    dispatch_sync(_queue, ^{
        @try {
#if __Debug_CloseAES == 0
            NSData* data = [NSKeyedArchiver archivedDataWithRootObject:dict];
            data = [data AES256EncryptWithKey:__AESKey];//加密
            [data writeToFile:filePath atomically:YES];
#else
            [dict writeToFile:filePath atomically:YES];
#endif
        } @catch (NSException *exception) {
            NSLog(@"saveNetCache Error: %@",exception);
        } @finally {
            
        }
    });
}

//读取数组
-(NSArray*)getLocalArrayWithFilePath:(NSString*)filePath{
    __block NSArray* array;
    dispatch_sync(_queue, ^{
#if __Debug_CloseAES == 0
        NSData* data = [[NSData alloc] initWithContentsOfFile:filePath];
        data = [data AES256DecryptWithKey:__AESKey];//解密
        array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
#else
        array = [NSArray arrayWithContentsOfFile:filePath];
#endif
    });
    return array;
}

//读取字典
-(NSDictionary*)getLcoalDictWithFilePath:(NSString*)filePath{
    
    __block NSDictionary* dict;
    dispatch_sync(_queue, ^{
#if __Debug_CloseAES == 0
        NSData* data = [[NSData alloc] initWithContentsOfFile:filePath];
        data = [data AES256DecryptWithKey:__AESKey];//解密
        dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
#else
        dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
#endif
    });
    return dict;
}


@end
